<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <!-- <el-button v-if="checkPermission('addEmployee')" size="small" type="primary" @click="isShowDialog = true">新增员工</el-button> -->
          <el-button :disabled="!checkPermission('addEmployee')" size="small" type="primary" @click="isShowDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employeeList">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="头像" prop="staffPhoto" width="200">
            <template #default="{row}">
              <img
                v-fiximg="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                alt=""
                style="width: 180px; height: 120px"
                @click="showCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployee" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template #default="obj">
              {{ obj.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template #default="obj">
              <!-- {{ obj.row.enableState }} -->
              <el-switch
                v-model="obj.row.enableState"
                :active-value="1"
                :inactive-value="2"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showAssignRole(row.id)">角色</el-button>
              <el-button v-if="checkPermission('delEmployee')" type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :page-size="pageConfig.size"
            :total="total"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <add-employee :is-show-dialog="isShowDialog" />
      <el-dialog title="二维码" :visible="isShowCode" @close="isShowCode = false">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <assign-role
        ref="assignRole"
        :is-show-dialog.sync="isShowAssignRole"
      />
    </div>
  </div>
</template>

<script>
import { delEmployee, getEmployeeList } from '@/api/employee'
import EnumEmployee from '@/api/constant/employees'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters'
import addEmployee from './components/add-employee.vue'
import QRCode from 'qrcode'
import assignRole from './components/assign-role.vue'
export default {
  components: {
    addEmployee,
    assignRole
  },
  data() {
    return {
      isShowAssignRole: false,
      isShowCode: false,
      pageConfig: {
        page: 1,
        size: 5
      },
      total: 0,
      employeeList: [],
      zidian: {
        '姓名': 'username',
        '手机号': 'mobile',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '入职时间': 'timeOfEntry'
      },
      isShowDialog: false
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async showAssignRole(id) {
      await this.$refs.assignRole.getCheckList(id)
      this.isShowAssignRole = true
    },
    showCode(url) {
      if (url) {
        this.isShowCode = true
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.myCanvas, url, {
            width: 300,
            color: {
              dark: '#66b1ff'
            }
          })
        })
      }
    },
    async delEmployee(id) {
      await this.$confirm('是否确认删除')
      await delEmployee(id)
      this.$message.success('删除成功')
      // 如果本来剩下一条数据, 删除成功获取新数据前,将页码减一
      if (this.employeeList.length === 1 && this.pageConfig.page > 1) {
        this.pageConfig.page--
      }
      this.getEmployeeList()
    },
    async exportExcel() {
      // 1. 获取员工数据
      const { rows } = await getEmployeeList({ page: 1, size: this.total })
      console.log(rows)
      // 2. 数据转换
      const data = rows.map(userObj => {
        return this.objToArray(userObj)
      })
      console.log(data)

      const header = Object.keys(this.zidian)
      // 3. 生成 excel
      export_json_to_excel({
        header,
        data
      })
    },
    objToArray(userObj) {
      console.log(userObj)
      const userArray = []

      // 遍历字典, 每个key都拿出英文字段, 去用户对象获取数据
      // 推入数组中, 最终可以形成顺序的用户数组
      for (const key in this.zidian) {
        const enKey = this.zidian[key]
        const value = userObj[enKey]
        // 不一定全部都是直接push到数组中,
        // 如果发现正在处理聘用形式或者入职时间
        // 需要额外改造数据
        if (enKey === 'formOfEmployment') {
          const obj = EnumEmployee.hireType.find(item => Number(item.id) === Number(value))
          userArray.push(obj ? obj.value : '未知')
        } else if (enKey === 'timeOfEntry') {
          userArray.push(formatDate(value))
        } else {
          userArray.push(value)
        }
      }
      console.log(userArray)
      // 转换逻辑
      return userArray
    },
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.pageConfig)
      this.total = total

      // 本地数据库没有 enableState 属性, 可以考虑获取数据是手动造假
      this.employeeList = rows.map(user => {
        const state = Math.round(Math.random())
        return {
          ...user,
          enableState: user.enableState || state
        }
      })
    },
    currentChange(newPage) {
      this.pageConfig.page = newPage
      this.getEmployeeList()
    },
    formatEmployee(row, col, cellVal) {
      // 将所有可能性, 逐个逐个列举出来的数据
      // 叫做枚举数据
      const obj = EnumEmployee.hireType.find(item => Number(item.id) === Number(cellVal))
      return obj ? obj.value : '未知'
    }
  }
}
</script>

<style>

</style>
